const express = require("express");
const router = express.Router();

// https://www.npmjs.com/package/lowdb 轻量级本地数据存储
const FileSync = require("lowdb/adapters/FileSync");
const adapter = new FileSync(__dirname + "/../lowdb/database.json");
const lowdb = require("lowdb"); const database = lowdb(adapter);
const shortid = require("shortid"); // 唯一字符串生成器

router.get("/", (req, res) => {
    res.redirect("/accounts");
}); // 根目录重定向至列表页
router.get("/accounts", (req, res) => {
    const accounts = database.get("accounts").value();
    res.render("accounts", { accounts });
}); // 记账簿项目列表模板
router.get("/account", (req, res) => {
    res.render("account");
}); // 记账簿项目创建模板
router.post("/account", (req, res) => {
    const account = { id: shortid.generate(), ...req.body };
    database.get("accounts").unshift(account).write(); // 新项目插入到最前
    res.redirect("/accounts"); // 项目创建操作完成后，跳转到列表页
}); // 记账簿项目创建操作
router.get("/account/:id", (req, res) => {
    database.get("accounts").remove({ id: req.params.id }).write();
    res.redirect("/accounts"); // 项目删除操作完成后，重新渲染列表
}); // 记账簿项目删除操作
module.exports = router;
